﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Web.UI;
using System.Web.UI.WebControls;

using BLL.AuthModel;
using Model.AuthModel;
using Util.Helper;
using Util.Configuration;
namespace UI.WebPage.PageBase
{
    /// <summary>
    /// 权限模型基类
    /// </summary>
    public class AuthModelPageBase : Page
    {
        #region 基类属性
        /// <summary>
        /// 成员对象
        /// </summary>
        protected StaffInfo LoginStaff = new StaffInfo();
        /// <summary>
        /// 页面操作行为
        /// </summary>
        protected string PageAction = string.Empty;
        /// <summary>
        /// 参数字典
        /// </summary>
        public Dictionary<string, string> QueryString = new Dictionary<string, string>();
        /// <summary>
        /// 母版页显示提示的标签控件
        /// </summary>
        public Label OperationMessage = new Label();
        #endregion

        #region 重载基类Page方法
        /// <summary>
        /// 覆盖页面加载事件
        /// </summary>
        /// <param name="e"></param>
        protected override void OnLoad(EventArgs e)
        {
            //先检查用户是否登录            
            if (this.CheckLogin())
            {
                string[] segments = Request.Url.Segments;   //0:/ 1:admin/ 2:system/ 3:add_module.aspx
                if (!segments[segments.Length - 2].Equals("main/"))
                {
                    string moduleLink = segments[segments.Length - 2] + segments[segments.Length - 1];
                    PageAction = Request.QueryString["action"] != null ? Request.QueryString["action"].ToLower() : "";
                    if (string.IsNullOrEmpty(PageAction))       //参数传递错误，退出
                    {
                        Response.Redirect(WebConfiguration.WebRoot + WebConfiguration.AdminRoot + "main/error.aspx?msg=" + Server.UrlEncode("权限参数传递错误"));
                        Response.End();
                    }
                    else if (!this.CheckAuth(moduleLink, PageAction))      //权限不足，退出
                    {
                        Response.Redirect(WebConfiguration.WebRoot + WebConfiguration.AdminRoot + "main/error.aspx?msg=" + Server.UrlEncode(string.Format("您不具备对页面{0}的{1}权限"
                            , moduleLink, PageAction)));
                        Response.End();
                    }
                    else
                        this.SetQueryString();                          //设置当前页面获取参数
                }
                if (this.Page.Master != null)
                    OperationMessage = (Label)this.Page.Master.FindControl("lblMessage");
            }
            else
            {
                Response.Redirect(WebConfiguration.WebRoot + WebConfiguration.AdminRoot + "main/login.aspx");
                Response.End();
            }
            base.OnLoad(e);
        }

        /// <summary>
        /// 覆盖页面报错事件
        /// </summary>
        /// <param name="e"></param>
        protected override void OnError(EventArgs e)
        {
            //string[] segments = Request.Url.Segments;
            //Exception objErr = Server.GetLastError().GetBaseException();
            //Server.ClearError();
            //Response.Redirect(WebConfiguration.AdminRoot + "main/error.aspx?msg=" + Server.UrlEncode(objErr.Message.ToString()) + "&url=" + Server.UrlEncode(Request.Url.PathAndQuery));
        }
        #endregion

        #region 私有方法，用户检查权限
        /// <summary>
        /// 检查成员是否登录
        /// </summary>
        /// <returns></returns>
        private bool CheckLogin()
        {
            LoginStaff = new StaffHelper().GetLoginStaff();
            if (LoginStaff.StaffID == 0 || string.IsNullOrEmpty(LoginStaff.Username))
                return false;
            return true;
        }
        /// <summary>
        /// 检查用户操作权限
        /// </summary>
        /// <param name="path">访问的路径</param>
        /// <param name="action">访问行为</param>
        /// <returns></returns>
        private bool CheckAuth(string moduleLink, string funcName)
        {
            return new StaffRolesBLL().CheckRolesAuthByStaff(LoginStaff.StaffID, moduleLink, funcName);
        }
        /// <summary>
        /// 初始化参数字典
        /// </summary>
        private void SetQueryString()
        {
            foreach (string key in Request.QueryString.AllKeys)
                if (!string.IsNullOrEmpty(key) && !key.Equals("action") && !key.Equals("page"))
                    QueryString.Add(key, Request.QueryString[key]);
        }
        #endregion

        #region 基类调用方法
        /// <summary>
        /// 设置提示信息
        /// </summary>
        /// <param name="lbl">Label控件</param>
        /// <param name="flag">结果标识</param>
        /// <param name="message">提示信息</param>
        public void SetMessage(bool flag, string message)
        {
            OperationMessage.CssClass = flag ? "success" : "error";
            if (flag)
                OperationMessage.Text = "操作成功：" + message;
            else
                OperationMessage.Text = "操作失败：" + message;
        }
        /// <summary>
        /// 获取字典参数值
        /// </summary>
        /// <param name="key">字典key</param>
        /// <returns></returns>
        public string GetQueryString(string key)
        {
            if (QueryString.ContainsKey(key))
                return QueryString[key];
            return "";
        }
        /// <summary>
        /// 返回全部字典参数值
        /// </summary>
        /// <returns></returns>
        public string GetQueryString()
        {
            StringBuilder repo = new StringBuilder();
            foreach (string key in QueryString.Keys)
                repo.AppendFormat("&{0}={1}", key, QueryString[key]);
            return repo.ToString();
        }
        /// <summary>
        /// 延时跳转
        /// </summary>
        /// <param name="url">跳转的目标页</param>
        /// <param name="timeout">延时的秒数</param>
        public void Redirect(string url, float timeout)
        {
            ClientScriptManager csm = this.Page.ClientScript;
            csm.RegisterClientScriptBlock(GetType(), "redirect", "<script type='text/javascript'>Init.redirect('" + url + "', " + timeout + ");</script>");
        }

        /// <summary>
        /// 提示信息，加回执事件
        /// </summary>
        /// <param name="message">提示信息</param>
        /// <param name="callback">回执事件</param>
        public void Redirect(string message, string callback)
        {
            ClientScriptManager csm = this.Page.ClientScript;
            csm.RegisterClientScriptBlock(GetType(), "redirect", "<script type='text/javascript'>alert('" + message + "');" + callback + "</script>");
        }

        /// <summary>
        /// 提示信息并延时跳转
        /// </summary>
        /// <param name="message"></param>
        /// <param name="url"></param>
        /// <param name="timeout"></param>
        public void Redirect(string message, string url, float timeout)
        {
            ClientScriptManager csm = this.Page.ClientScript;
            csm.RegisterClientScriptBlock(GetType(), "redirect", "<script type='text/javascript'>alert('" + message + "');Init.Redirect('" + url + "', " + timeout + ");</script>");
        }

        /// <summary>
        /// 记录管理员操作记录
        /// </summary>
        /// <param name="message"></param>
        public void WriteStaffAccess(string message)
        {
            //new BLL.AuthModel.AuthBLL.StaffAccessBLL().InsertAccess(LoginStaff, message);            
        }
        /// <summary>
        /// 转换页面行为提示文字
        /// </summary>
        /// <returns></returns>
        public string ConvertAction()
        {
            switch (PageAction)
            {
                case "add": return "新增";
                case "update": return "修改";
                case "clone": return "克隆";
                case "list": return "列表";
                case "delete": return "删除";
                default: return "";
            }
        }
        /// <summary>
        /// 转换页面行为提示文字
        /// </summary>
        /// <param name="pageName"></param>
        /// <returns></returns>
        public string ConvertAction(string pageName)
        {
            switch (PageAction)
            {
                case "add": return "新增" + pageName;
                case "update": return "修改" + pageName;
                case "clone": return "克隆" + pageName;
                case "list": return pageName + "列表";
                case "delete": return "删除" + pageName;
                default: return "";
            }
        }
        /// <summary>
        /// html转码
        /// </summary>
        /// <param name="text"></param>
        /// <returns></returns>
        public string HtmlEncode(TextBox text)
        {
            return Server.HtmlEncode(text.Text.Trim());
        }
        /// <summary>
        /// html转码
        /// </summary>
        /// <param name="text"></param>
        /// <returns></returns>
        public string HtmlEncode(string text) 
        {
            return Server.HtmlEncode(text.Trim());
        }
        /// <summary>
        /// html反转码
        /// </summary>
        /// <param name="text"></param>
        /// <returns></returns>
        public string HtmlDecode(string text)
        {
            return Server.HtmlDecode(text);
        }
        #endregion
    }
}
